import { Layout } from "@/components/layout/layout";
import withAuth, { getServerSideProps } from "@/hoc/withAuth";
import { useHttp } from "@/hooks";
import useMounted from "@/hooks/useMounted";
import type { NextPage, GetServerSidePropsContext } from "next";
import { useRouter } from "next/router";
import { useEffect, useRef, useState } from "react";
import React from "react";
import {
  Table,
  TableHeader,
  TableColumn,
  TableBody,
  TableRow,
  TableCell,
  getKeyValue,
  Button,
  Image,
  Chip,
  Avatar,
  Link,
} from "@nextui-org/react";
import { User } from "@/entities/User";
import { capitalize } from "@/utils/base";
import dayjs from "dayjs";
import DatasetModal from "@/components/modal/datasetModal";
import { App } from "@/entities/App";
import { Dataset } from "@/entities/Dataset";
import {
  Add,
  AddBoxOutlined,
  AddCircleOutline,
  AddSharp,
  BlockSharp,
  CheckCircleOutline,
} from "@mui/icons-material";
import UserModal from "@/components/modal/userModal";

const DatasetsPage: NextPage = () => {
  const [datasets, setDatasets] = useState<Dataset[]>([]);
  const [visible, setVisible] = useState(false);

  const [userModalVisible, setUserModalVisible] = useState(false);
  const { http } = useHttp();
  const [curDatasetId, setCurDatasetId] = useState<number>();

  const router = useRouter();
  const { appid } = router.query;

  const getDatasetList = async (silent = false) => {
    const res = await http.get(
      "/api/dataset/list",
      { appid },
      { isOpenLoading: true, silent }
    );
    if (res?.success) {
      setDatasets(res.data.datasets as Dataset[]);
    }
  };

  const getDatasetListRef = useRef(getDatasetList);

  useMounted(() => {
    getDatasetListRef.current();
  });

  const cols = [
    "id",
    "name",
    "introduce",
    "value",
    "defValueId",
    "app",
    "editor",
    "updatedAt",
    "operation",
  ];
  const getWidth = (key: string) => {
    if (key === "operation") {
      return 300;
    } else if (key === "id") {
      return 100;
    } else if (key === "introduce") {
      return 300;
    } else if (key === "value") {
      return 600;
    } else {
      return 100;
    }
  };
  const columns = cols.map((col) => ({
    key: col,
    width: getWidth(col),
    label:
      col == "isDelete"
        ? "Status"
        : col === "defValueId"
        ? "Default Id"
        : capitalize(col.replace(/[A-Z]/g, " $&")),
  }));

  const getVal = (item: Dataset, key: string | number) => {
    // debugger;
    const val = getKeyValue(item, key);
    if (key === "app") {
      const app = val as App;
      return (
        <Chip size="sm" color={"success"} variant="flat">
          {app.name}
        </Chip>
      );
    } else if (key === "name") {
      return (
        <Link color="primary" href={`/datasets/endpoints?datasetid=${item.id}`}>
          {val}
        </Link>
      );
    } else if (["createdAt", "updatedAt"].includes(key.toString())) {
      const day = dayjs(val).format("YYYY-MM-DD HH:mm:ss");
      return day;
    } else if (key === "editor") {
      const editor = val as User;
      return (
        <Chip
          size="sm"
          startContent={
            <Avatar
              className="w-4 h-4"
              name={editor.name}
              src={editor.avatarData}
            />
          }
          color={"success"}
          variant="flat"
        >
          {editor.name}
        </Chip>
      );
    } else {
      return val;
    }
  };

  const onCreated = (success: boolean) => {
    success && getDatasetListRef.current(true);
  };

  const handleEdit = (id: number) => {
    setCurDatasetId(id);
    setVisible(true);
  };

  return (
    <div className="datasets-page px-6 py-3">
      <DatasetModal
        mode="edit"
        visible={visible}
        closeCallback={() => setVisible(false)}
        datasetId={curDatasetId}
        confirmCallback={onCreated}
      />

      <div className="actions text-right mb-4">
        <DatasetModal mode="create" confirmCallback={onCreated} />
      </div>
      <Table className="text-center" aria-label="apps table">
        <TableHeader columns={columns}>
          {(column) => (
            <TableColumn
              className="text-center"
              align="end"
              allowsResizing
              width={column.width ?? 100}
              key={column.key}
            >
              {column.label}
            </TableColumn>
          )}
        </TableHeader>
        <TableBody items={datasets} emptyContent="no data">
          {(item) => (
            <TableRow key={item.id}>
              {(columnKey) =>
                columnKey === "operation" ? (
                  <TableCell>
                    <Button
                      variant="flat"
                      className="m-2 rounded-md"
                      size="sm"
                      color="primary"
                      onClick={() => handleEdit(item.id)}
                    >
                      Edit
                    </Button>
                  </TableCell>
                ) : (
                  <TableCell>
                    <div
                      className={
                        "cell-value " +
                        (["introduce", "value"].includes(columnKey as string)
                          ? "line-clamp-2"
                          : "")
                      }
                    >
                      {getVal(item, columnKey)}
                    </div>
                  </TableCell>
                )
              }
            </TableRow>
          )}
        </TableBody>
      </Table>
    </div>
  );
};

export { getServerSideProps };

export default withAuth(DatasetsPage);
